<template>
  <div class="m-25 mt-65">
    <div class="normal-box-mod">

        <!-- title -->
        <div class="normal-box-hd clearfix">
            <div class="normal-box-title">
            <div class="decorate-square"></div>
            <h2>管理员管理</h2>
            </div>
        </div>

        <!-- 搜索 -->
        <div class="normal-box-bd">
            <div class="clearfix mb-20">
                <Button custom-icon="iconfont icon-fangkuai2" type="primary" size="small" style="float:right"  @click="show_create">添加管理员</Button>
                <Input class="mr-10" v-model="queryData.name" :clearable=true placeholder="管理员姓名" style="width: 200px"/>
                <Input class="mr-10" v-model="queryData.phone" :clearable=true placeholder="电话" style="width: 200px"/>
                <Col span="4" class="mr-10">
                <sele @ProvinceData="childByValue_"></sele>
              </Col>
                <Button type="primary" custom-icon="iconfont icon-chaxun"  size="small" @click="getList">查找</Button>
            </div>
        </div>


        <div>
            <i-table stripe highlight-row border :content="self" :columns="Tcolumns" :data="adminList"></i-table>
        </div>
        <div class="page">
          <Page :total="queryData.totalRecord" :page-size="queryData.limit" :current="queryData.page" show-total show-elevator @on-change="changepage"></Page>
        </div>

        <!--新建/修改用户-->
        <Modal v-model="newAdmin.show_modal" :title="newAdmin.modal_title" :loading="newAdmin.loading"
          @on-ok="sendPost">
          <Form ref="check" :model="newAdmin.data"
            :label-width="82">

            <FormItem label="管理员姓名" prop="name" :rules="newAdmin.rules.name">
              <Input placeholder="请输入" v-model="newAdmin.data.name" style="width:300px;"/>
            </FormItem>

            <FormItem label="区域级别" prop="userType" :rules="newAdmin.rules.userType">
                <Select v-model="newAdmin.data.userType" style="width:300px">
                    <Option v-for="item in admin_lv" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
            </FormItem>

            <FormItem label="账号状态" prop="review" :rules="newAdmin.rules.review">
              <Select v-model="newAdmin.data.review" style="width:300px">
                    <Option value="0">未审核</Option>
                    <Option value="1">正常</Option>
                    <Option value="2">暂停服务</Option>
              </Select>
            </FormItem>

            <FormItem label="性别" prop="sex">
                <Radio-group v-model="newAdmin.data.sex">
                    <Radio label="1">男</Radio>
                    <Radio label="0">女</Radio>
                </Radio-group>
            </FormItem>

            <FormItem label="手机号码" prop="mobilephone" :rules="newAdmin.rules.mobilephone">
              <Input placeholder="请输入" v-model="newAdmin.data.mobilephone" style="width:300px;"/>
            </FormItem>

            <FormItem label="联系地址" prop="address" :rules="newAdmin.rules.address">
              <Input placeholder="请输入" v-model="newAdmin.data.address" style="width:300px;"/>
            </FormItem>

            <FormItem label="管辖区域">
              <Col span="18" class="mr-10">
                <sele @ProvinceData="childByValue"></sele>
              </Col>
            </FormItem>

            <FormItem label="备注" prop="remark" :rules="newAdmin.rules.remark">
              <Input placeholder="请输入" v-model="newAdmin.data.remark" style="width:300px;"/>
            </FormItem>

          </Form>
        </Modal>

        <!-- 身份管理 -->
        <Modal v-model="sf_ctrl.show_modal" :title="sf_ctrl.modal_title" :loading="sf_ctrl.loading"
          @on-ok="SF">
          <Form ref="check_sf" :model="sf_ctrl.data" :label-width="82" :rules="sf_ctrl.rules">

            <FormItem label="姓名" prop="name">
              <Input placeholder="请输入" v-model="sf_ctrl.data.name" style="width:300px;"/>
            </FormItem>

            <FormItem label="身份" prop="userSf">
              <Select v-model="sf_ctrl.data.userSf" style="width:300px">
                  <Option v-for="item in admin_sf" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>

            <FormItem label="操作" prop="type">
                <Radio-group v-model="sf_ctrl.data.type">
                    <Radio label="bind">绑定身份</Radio>
                    <Radio label="untie">解绑身份</Radio>
                </Radio-group>
            </FormItem>

            <FormItem label="回收编码" prop="roCompanyCode">
              <Input placeholder="15位，仅村口回收" v-model="sf_ctrl.data.roCompanyCode" style="width:300px;"/>
            </FormItem>

          </Form>
        </Modal>

    </div>
  </div>
</template>

<script>
import adminApi from "@/api/pingHu/admin.js";
import moment from "moment";
import { Message } from "iview";
import sele from "@/view/test/city.vue"
export default {
  components: {
    sele
  },
  data() {
    return {
      adminList: [],
      keyWords: '',  // 搜索关键字
      disabled: false, // 输入禁用
      index: '',  // 当前编号
      // 新增管理员
      newAdmin:  {
          show_modal: false,
          is_create: true,
          loading: true,
          modal_title: "添加管理员",
          rules: {   // check
            name:     [{ required: true, message: "请填写管理员姓名", trigger: "blur"}],
            review:   [{required: true, message: "请选择账号状态", trigger: "change"}],
            userType: [{required: true, message: "请选择区域级别", trigger: "change"}],
            remark:   [{required: true, message: "请填写备注", trigger: "blur"}],
            address:  [{ required: true, message: "请填写详细地址", trigger: "blur"}],
          },
          data: {
            name: "",
            remark: "",
            address: "",
            mobilephone: "",
            userType: '',
            review: '',
            sex: '1',
          }
        },

      // 身份管理数据
      sf_ctrl: {
        show_modal: false,
        loading: true,
        modal_title: "身份管理",
        rules: {
          name:   [{ required: true, message: "请填写管理员姓名", trigger: "blur"}],
          userSf: [{ required: true, message: "请选择管理员身份", trigger: "blur"}],
        },
        data: {
          id: '',
          name: '',
          userSf: '',
          roCompanyCode: '',
          type: 'bind'
        }

      },

      // 管理员等级选择器选项
      admin_lv: [
          {label: '街道镇管理员', value: "strt"},
          {label: '社区村管理员', value: "comm"},
          {label: '小区管理员', value: "commin"},
          {label: '普通用户', value: "home"},
      ],
      // 管理员身份选项
      admin_sf: [
        {label: '政府工作/村口服务', value: 'CKGMWK'},
        {label: '村口之家', value: 'CKHCAD'},
        {label: '垃圾巡检/村口巡检', value: 'CKGIAD'},
        {label: '机器巡检', value: 'CKMIAD'},
        {label: '机器维修', value: 'CKMSAD'},
        {label: '村口公益', value: 'CKPWAD'},
        {label: '村口支付/村口生活', value: 'CKPAYA'},
        {label: '村口回收/收呗', value: 'CKROAD'},
        {label: '村口百货', value: 'CKUBAD'},
        {label: '物业管理员', value: 'CKWUYE'},
      ],

      // 获取数据配置
      queryData: {
        limit: 10,
        page: 1,
        totalRecord: 0,
        userId: '',
        name: "",
        phone: '',
      },

      // 表格配置
      self: this,
      Tcolumns: [
        { align:"center", title: "编号", key: "id", width: 80},
        { align:"center", title: "管理员账号", key: "loginname", width: 120},
        { align:"center", title: "姓名", key: "name",width:144},
        { align:"center", title: "管理员身份", key: "userSf",width:145},
        { // 账号状态
          align:"center",
          title: "账号状态",
          width: 100,
          render: (create, params)=> {
            let s = Number(params.row.review)
            let color = ''
            let text = ''
            switch(s) {
                    case 0: color = '#fbb217';text = '未审核';break;
                    case 1: color = '#02d792';text = '正常';break;
                    case 2: color = '#ff4366';text = '暂停服务';break;
                    default: text = '状态返回异常'
                }
            return create('div',{
              style: {
                background: color,
                color: s==0?'#000':'#fff',
                borderRadius: '20px'
              },
            },text)
          }
        },
        { align:"center", title: "管理员类型", key: "userType",width: 97},
        { align:"center", title: "管辖区域", key: "commname",width: 120,},
        { align:"center", title: "性别", key: "sex",width: 70,},
        { align:"center", title: "备注", key: "remark", width: 150},
        { align:"center", title: "电话", key: "mobilephone", width: 120},
        { align:"center", title: "注册时间", key: "registertime", width: 160},

        { // 操作
          title: '操作',
          key: 'action',
          width: 320,
          align: 'center',
          render: (create, params)=> {
              // 创建父节点
              return create('div',[
                  // 初始化密码
                  create('i-button',{
                      props: { type: 'info', size: 'small',},
                      style: {margin: '0 3px'},
                      on: {
                          click:()=> {
                              this.initPass(params.row)
                          }
                      }
                  },'初始化密码'),

                  // 身份管理
                  create('i-button',{
                      props: { type: 'success', size: 'small',},
                      style: {margin: '0 3px'},
                      on: {
                          click:()=> {
                              this.show_sf(params.row)
                          }
                      }
                  },'身份管理'),

                  // 修改按钮
                  create('i-button',{
                      props: { type: 'primary', size: 'small',},
                      style: {margin: '0 3px'},
                      on: {
                          click:()=> {
                              this.show_update(params.row.id)
                          }
                      }
                  },'修改'),

                  // 删除按钮
                  create('i-button',{
                      props: { type: 'error', size: 'small'},
                      style: {margin: '0 3px'},
                      on: {
                          click:()=> {
                              this.remove(params.row)
                          }
                      }
                  },'删除'),

              ])
          }
        }

      ],

    };
  },
  async created() {
    await setTimeout({},1000)
    let area = window.defArea
    this.queryData.provid = area[0]
    this.queryData.cityid = area[1]
    this.queryData.distid = area[2]
    this.getList();
  },
  methods: {
    // 获取管理员列表
    async getList() {
      let data = (await adminApi('get',this.queryData,'page')).data;
      console.log('列表：',data);
      this.queryData.totalRecord = data.totalRecord;
      this.adminList = data.list
    },

    // 分页切换
    changepage(index) {
      this.queryData.page = index;
      this.getList();
    },

    // 新建用户模态框
    show_create() {
      this.disabled = false
      this.newAdmin.rules.mobilephone = [
        { required: true, min: 11, max: 11, message: "请填写正确的手机号", trigger: "blur"},
        { type: 'number', trigger: "blur", message: "手机号码格式错误", transform(value)
        {return Number(value);}},]
      let qwq = this.newAdmin
      this.$refs["check"].resetFields(); // 清空内容
      qwq.is_create = true;
      qwq.modal_title = "添加用户";
      qwq.show_modal = true; // 模态框显示
    },

    // 修改用户模态框
    async show_update(index) {
      this.index = index
      this.newAdmin.rules.mobilephone = []
      this.$refs["check"].resetFields();
      this.disabled = true
      let qwq = this.newAdmin
      qwq.rules.id = []
      qwq.is_create = false;
      qwq.modal_title = "修改管理员";
      this.queryData.userId = index
      let data = (await adminApi('get',undefined,`${index}`)).data
      this.clearQuery()
      console.log('本条数据：',data);

      // 数据填充
      let userData = this.newAdmin.data
      userData.id = data.id
      userData.sex=='男 '?data.sex='1':data.sex='0'
      userData.name = data.name
      userData.userType = data.userType
      userData.review = data.review
      userData.remark = data.remark
      userData.address = data.address
      userData.mobilephone = data.mobilephone

      userData.mobilephone = Number(data.mobilephone)
      qwq.show_modal = true; // 模态框显示
    },

    // 查询清空
    clearQuery() {
      this.queryData.userId = ''
      this.queryData.name = ''
      this.queryData.phone = ''
    },

    // 用户数据提交
    sendPost() {
      this.$refs["check"].validate(async valid => {
        if(!valid) {
          this.changeLoading()
          console.log('no');
          return
        }
        if(valid) {
          let qwq = this.newAdmin.is_create?'post':'put'
          let url = this.newAdmin.is_create?'':`${this.index}`
          let data = (await adminApi(qwq,this.newAdmin.data,url))
          let result = data.data
          let message = data.message
          if(result) {
            this.$Message.success("操作成功")
            // console.log(result);
            this.getList()
            this.newAdmin.show_modal = false
            return
          }
          console.log(result);
          this.$Message.error(message)
        }

      })
    },
    // 身份管理显示
    show_sf(index) {
      this.$refs["check_sf"].resetFields();
      let qwq = this.sf_ctrl
      qwq.data.id = index.id
      qwq.data.name = index.name
      qwq.show_modal = true; // 模态框显示
    },
    // 身份管理提交
    async SF() {
      this.$refs["check_sf"].validate(async valid => {
        if(!valid) {
          this.changeLoading()
          return
        }
        if(valid) {
          let data = (await adminApi('get',this.sf_ctrl.data,'binding'))
          let result = data.data
          let message = data.message
          if(result) {
            this.$Message.success(result)
            this.getList()
            this.sf_ctrl.show_modal = false
            return
          }
          this.$Message.error(message)
        }

      })
    },


    // 密码初始化
    initPass(index) {
      const _id = String(index.id);
      const _name = index.name;
      this.$Modal.confirm({
        title: "初始化确认",
        content:
          "<p>你确认要将管理员 <strong>" + _name +
          "</strong> 的密码初始化吗？</p>",
        loading: true,
        onOk: async () => {
          let data = (await adminApi('get',undefined,`pwd/${_id}`))
            let result = data.data
            let msg = data.message
            if(result) {
              this.$Message.success("操作成功")
              this.getList()
              this.$Modal.remove();
              return
            }
            this.$Message.error(msg)
            this.$Modal.remove();
        }
      });
    },

    // 改变load状态
    changeLoading() {
      this.newAdmin.loading = false;
      this.sf_ctrl.loading = false;
      this.$nextTick(() => {
        this.newAdmin.loading = true;
        this.sf_ctrl.loading = true;
      });
    },

    // 删除
    remove(index) {
     const _id = String(index.id);
      const _name = index.name;
      this.$Modal.confirm({
        title: "删除确认",
        content:
          "<p>你确认要删除管理员姓名为 <strong>" + _name +
          "</strong> 的记录吗？</p>",
        loading: true,
        onOk: async () => {
            let data = (await adminApi('delete',undefined,_id))
            let result = data.data
            let message = data.message
            if(result) {
              this.$Message.success("操作成功")
              this.getList()
              this.$Modal.remove();
              return
            }
            this.$Message.error(message)
            this.$Modal.remove();
        }
      });

    },

    // 六级联动数据获取
    childByValue(newObject) {
        let area = this.newAdmin.data
        area.provid = newObject.provid||'';
        area.cityid = newObject.cityid||'';
        area.distid = newObject.distid||'';
        area.strt = newObject.strtid||'';
        area.commid = newObject.commid||'';
        area.comminid = newObject.comminid||'';
    },
    childByValue_(newObject) {
        let area = this.queryData
        area.provid = newObject.provid||'';
        area.cityid = newObject.cityid||'';
        area.distid = newObject.distid||'';
        area.strt = newObject.strtid||'';
        area.commid = newObject.commid||'';
        area.comminid = newObject.comminid||'';
    },


  },

};
</script>

<style>
    td[class="y ivu-table-column-center"] {background: #02D792 !important; color: #fff;}
    td[class="n ivu-table-column-center"] {background: #f00 !important; color: #fff;}
    .page {padding: 1em .5em;}
</style>
